/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lansupportserver;

import ObjectHandler.LanSupportMessage;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.Socket;
import java.nio.ByteBuffer;
import javax.swing.JOptionPane;

/**
 *
 * @author Quan
 */
public class MyKeyListener implements KeyListener {

    private Socket sendSocket;

    public MyKeyListener(Socket sendSocket) {
        this.sendSocket = sendSocket;
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        LanSupportMessage lanSupportMessage = new LanSupportMessage(LanSupportMessage.keyPress);
        byte[] KeyCode = _long2Bytes(e.getKeyCode());
        lanSupportMessage.setData(KeyCode);
        lanSupportMessage.Send(sendSocket);
        System.out.println(String.valueOf(KeyCode));
    }

    @Override
    public void keyReleased(KeyEvent e) {
        LanSupportMessage lanSupportMessage = new LanSupportMessage(LanSupportMessage.keyRelease);
        byte[] KeyCode = _long2Bytes(e.getKeyCode());
        lanSupportMessage.setData(KeyCode);
        lanSupportMessage.Send(sendSocket);
        System.out.println(String.valueOf(KeyCode));
    }

    private long _bytes2Long(byte[] bs) {
        long value = 0;
        for (int i = 0; i < bs.length; i++) {
            byte c = bs[i];
            value = (value << 8) + (c & 0xff);
        }
        return value;
    }

    private byte[] _long2Bytes(long l) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(8);
        byteBuffer.putLong(l);
        byte[] byteResult = byteBuffer.array();
        return byteResult;
    }
}
